#!/usr/bin/env python
import cgi
import datetime
import wsgiref.handlers
import json
import os
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from google.appengine.ext.webapp import template

class Edamame(db.Model):
  author = db.UserProperty()
  title = db.StringProperty(multiline=True)
  comment = db.TextProperty()
  content = db.TextProperty()
  date = db.DateTimeProperty(auto_now_add=True)
  def id(self):
        return self.key().id()
    
class MainPage(webapp.RequestHandler):
  def get(self):
    template_values = {
                       "user":users.get_current_user(),
    }
    path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
    self.response.out.write(template.render(path, template_values))
    
class EdamamePage(webapp.RequestHandler):
  def get(self):
    edamame = Edamame.get_by_id(int(self.request.get("id")))
    if edamame.author and ( edamame.author != users.get_current_user()):
        self.redirect('/')
        return
    template_values = {
                       "id":cgi.escape(self.request.get("id")),
                       "title":edamame.title,
                       "user":users.get_current_user(),
                       "comment":edamame.comment
    }
    path = os.path.join(os.path.dirname(__file__), 'templates/edamame.html')
    self.response.out.write(template.render(path, template_values))
    
class RunPage(webapp.RequestHandler):
  def get(self):
    edamame = Edamame.get_by_id(int(self.request.get("id")))
    template_values = {
                       "id":cgi.escape(self.request.get("id")),
                       "title":edamame.title,
                       "user":users.get_current_user(),
                       "author":edamame.author,
                       "comment":edamame.comment
    }
    path = os.path.join(os.path.dirname(__file__), 'templates/run.html')
    self.response.out.write(template.render(path, template_values))
    
class GoogleGadgetPage(webapp.RequestHandler):
  def get(self):
    edamame = Edamame.get_by_id(int(self.request.get("id")))
    template_values = {
                       "id":cgi.escape(self.request.get("id")),
                       "title":edamame.title,
    }
    path = os.path.join(os.path.dirname(__file__), 'templates/googleGadget.xml')
    self.response.out.write(template.render(path, template_values))
    
class DeleteEdamamePage(webapp.RequestHandler):
  def get(self):
    edamame = Edamame.get_by_id(int(self.request.get("id")))
    if edamame.author and ( edamame.author != users.get_current_user()):
       self.redirect('/list')
       return
    edamame.delete()
    self.redirect('/list')
    
class ListPage(webapp.RequestHandler):
  def get(self):
    query = Edamame.all().order("date")
    edamames = query.fetch(300)
    template_values = {
                       "edamames":edamames,
                       "user":users.get_current_user()
    }
    path = os.path.join(os.path.dirname(__file__), 'templates/list.html')
    self.response.out.write(template.render(path, template_values))
    
class MyListPage(webapp.RequestHandler):
  def get(self):
    query = Edamame.all().order("date").filter("author", users.get_current_user())
    edamames = query.fetch(300)
    template_values = {
                       "edamames":edamames,
                       "user":users.get_current_user()
    }
    path = os.path.join(os.path.dirname(__file__), 'templates/list.html')
    
    self.response.out.write(template.render(path, template_values))
class Proxy(webapp.RequestHandler):
    def get(self):
        url = self.request.get("url")
        result = urlfetch.fetch(url)
        self.response.out.write(result.content)
        
class DeleteEdamamePage(webapp.RequestHandler):
  def get(self):
    edamame = Edamame.get_by_id(int(self.request.get("id")))
    if edamame.author and ( edamame.author != users.get_current_user()):
       self.redirect('/list')
       return
    edamame.delete()
    self.redirect('/list')
    
class CreateEdamamePage(webapp.RequestHandler):
  def get(self):
    if users.get_current_user():
        edamame = Edamame()
        edamame.author = users.get_current_user()
    else:
        self.redirect(users.create_login_url("/create"))
        return
    if self.request.get("id"):
        edamameBase = Edamame.get_by_id(int(self.request.get("id")))
        edamame.content = edamameBase.content
        edamame.title = edamameBase.title
        edamame.comment = edamameBase.comment
    edamame.put()
    self.redirect('/edamame?id=%d' % edamame.key().id())
    
class LoginPage(webapp.RequestHandler):
  def get(self):
    self.redirect(users.create_login_url("/"))
    
class LogoutPage(webapp.RequestHandler):
  def get(self):
    self.redirect(users.create_logout_url("/"))
application = webapp.WSGIApplication([
  ('/', MainPage),
  ('/list', ListPage),
  ('/login', LoginPage),
  ('/logout', LogoutPage),
  ('/mylist', MyListPage),
  ('/run', RunPage),
  ('/edamame', EdamamePage),
  ('/create', CreateEdamamePage),
  ('/delete', DeleteEdamamePage),
  ('/googleGadget', GoogleGadgetPage),
  ('/proxy', Proxy)
  
  
], debug=True)

def main():
  wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
  main()
 